package com.example.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 项目启动 监听主题
 *
 */
@Slf4j
//@Component
public class MqttClientListener implements ApplicationListener<ContextRefreshedEvent> {


    private volatile AtomicBoolean isInit=new AtomicBoolean(false);

    private String mqttId = "1";
    private String mqttClientId= "dkdf";
    private String host = "tcp://47.103.101.18:1883";
    private String username = "";
    private String password = "";
    private String topic = "seaLevel";

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            //防止重复触发
            if(!isInit.compareAndSet(false,true)) {
                return;
            }
            MqttClientConnect mqttClientConnect = new MqttClientConnect();
            mqttClientConnect.setMqttClientId(mqttId);
            mqttClientConnect.setMqttClient(host, mqttClientId, username, password, false, new MqttClientCallback(mqttId));
            mqttClientConnect.sub(StringUtils.commaDelimitedListToStringArray(topic));
            MqttClientConnect.mqttClients.put(mqttId, mqttClientConnect);
            log.info("{}--连接成功！！订阅主题--{}", mqttId, topic);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
